#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
发送电子邮件的方法
script name: email
Created on 2020/1/5 16:59 by PyCharm
@author: fujianjian
"""
from threading import Thread

from flask import current_app, render_template
from flask_mail import Message

from app import mail


def send_async_email(app, msg):
    """
    异步发送电子邮件
    :param app:
    :param msg:
    :return:
    """
    with app.app_context():
        mail.send(msg)


def send_email(to, subject, template, **kwargs):
    """
    发送电子邮件包装类
    :param to:
    :param subject:
    :param template:
    :param kwargs:
    :return:
    """
    app = current_app._get_current_object()
    msg = Message(app.config['FLASK_MAIL_SUBJECT_PREFIX'] + subject, sender=app.config['FLASK_MAIL_SENDER'], to=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr
